import json
from django.contrib.auth.models import User
from myApp.models import *
from utils.getPublicData import *
from datetime import datetime
from utils.error import *
import csv
import re
from snownlp import SnowNLP

from wordAna.wordAnaTwo import result

allData = getAllData()

def getMaxRate():
    ratelist=[x.rate for x in allData]
    titlelist=[x.title for x in allData]
    maxRate=max(map(float,ratelist))
    maxTitle=titlelist[ratelist.index(str(maxRate))]
    return maxRate,maxTitle

def getMaxCommentlen():
    commentlenlist=[x.comment for x in allData]
    maxCommentlen=max(map(int,commentlenlist))
    return maxCommentlen

def getMaxMovieTime():
    MovieTimelist = [x.movietime for x in allData]
    maxMovieTime = max(map(int, MovieTimelist))
    return maxMovieTime

def getMinTime():
    timelist = [x.uptime for x in allData if x.uptime != "未知时间"]
    now = datetime.now()
    date_objects = []
    for date in timelist:
        try:
            date_objects.append(datetime.strptime(date, '%Y-%m-%d'))
        except (ValueError, TypeError):
            continue
    if not date_objects:
        print("没有有效时间数据可比较")
        return None
    minTime = min(date_objects, key=lambda x: abs(x - now))
    minTime = minTime.strftime('%Y-%m-%d')
    return minTime

def getTypeAll():
    type={}
    for i in allData:
        for j in i.type:
            if type.get(j,-1)==-1:
                type[j]=1
            else:
                type[j] += 1
    maxTypelen=len(list(type.values()))
    maxType=max(type.keys(), key=lambda k: type[k])
    return maxType,maxTypelen

def getAllRateData():
    dataDic={}
    for i in allData:
        if dataDic.get(float(i.rate),-1)==-1:
            dataDic[float(i.rate)] = 1
        else:
            dataDic[float(i.rate)] += 1
    dataDic=sorted(dataDic.items(), key=lambda x:x[0], reverse=True)
    xData=[]
    yData=[]
    for i in dataDic:
        xData.append(i[0])
        yData.append(i[1])
    return xData[:10],yData[:10]

def getAllUser():
    allUser=list(Users.objects.all())
    userDic={}
    for i in allUser:
        if userDic.get(i.username, -1)==-1:
            userDic[i.username] = 1
    userPieData=[]
    for k,v in userDic.items():
        userPieData.append({'name':k,'value':v})
    return userPieData

def getAllMovies():
    movieList=[]
    for i in allData:
        movieList.append(i.title)
    return movieList

def getMovieInfoDetail(movieName):
    movieInfo={}
    for i in allData:
        if i.title == movieName:
            movieInfo=i
    return movieInfo

def changeSelfInfo(newInfo, fileInfo, username):
    user = Users.objects.get(username=username)
    user.info = newInfo.get('info')
    if fileInfo.get('avatar') is not None:
        user.avatar = fileInfo.get('avatar')
    user.save()

def changePasswordTwo(username, passwordInfo):
    oldPwd = passwordInfo['oldPassword']
    newPwd = passwordInfo['newPassword']
    checkPwd = passwordInfo['checkPassword']
    user = Users.objects.get(username=username)
    if oldPwd != user.password:return '原密码不正确'
    if newPwd != checkPwd:return '密码确认失败'
    user.password = newPwd
    user.save()

def getMovieById(id):
    movieInfo = []
    for i in allData:
        if int(i.id) == int(id):
            movieInfo = i
    print(movieInfo.title)
    return movieInfo

def getPostData(word):
    movieInfos = Movies.objects.filter(title__contains=word)
    def map_fn(item):
        item.rate=float(item.rate) * 10
        # 类型
        item.type=item.type.split(',')

        if item.country==None:
            item.country='中国大陆'
        else:
            item.country=item.country.split(',')

        if item.language==None:
            item.language='汉语普通话'
        else:
            item.language=item.language.split(',')
        #星级
        item.starts = item.starts.split('%.')
        def add_a(list):
            return [x + '%' for x in list]
        item.starts = add_a(item.starts)

        #图片
        item.imglist = item.imglist.split('.https')
        def fix_urls(url_list):
            fixed = []
            for i, url in enumerate(url_list):
                if i == 0:
                    fixed.append(url)
                else:
                    fixed.append(f"https{url}")
            return fixed
        item.imglist = fix_urls(item.imglist)

        item.comments = json.loads(item.comments)
        return item
    movieInfos = list(map(map_fn, list(movieInfos)))
    return movieInfos

def getTypePieChatData():
    typeData = {}
    for i in allData:
        for j in i.type:
            if typeData.get(j, -1) == -1:
                typeData[j] = 1
            else:
                typeData[j] += 1
    typePieData = []
    for k, v in typeData.items():
        typePieData.append({
            'name': k,
            'value': v
        })
    return typePieData[:10]

def getTypeBarChatData():
    typeData = {}
    for i in allData:
        for j in i.type:
            if typeData.get(j, -1) == -1:
                typeData[j] = 1
            else:
                typeData[j] += 1
    rateData = {}
    for k, v in typeData.items():
        if rateData.get(k, -1) == -1:
            rateData[k] = []
    for i in allData:
        for key, value in rateData.items():
            for j in i.type:
                if j == key:
                    value.append(float(i.rate))
    for key, value in rateData.items():
        sum = 0
        for item in value:
            sum += item
        rateData[key] = round(sum / len(value), 1)
    return list(typeData.keys()),list(typeData.values()),list(rateData.values())

def getCountryChartData():
    countryDic = {}
    for i in allData:
        for j in i.country:
            if countryDic.get(j, -1) == -1:
                countryDic[j] = 1
            else:
                countryDic[j] += 1
    countrySortData=sorted(countryDic.items(), key=lambda x:x[1], reverse=True)[:10]
    countryX = []
    countryY = []
    for i in countrySortData:
        countryX.append(i[0])
        countryY.append(i[1])
    return countryX, countryY

def getLangChartData():
    languageData = {}
    for i in allData:
        for j in i.language:
            if languageData.get(j, -1) == -1:
                languageData[j] = 1
            else:
                languageData[j] += 1
    languageDataEnd = []
    for k, v in languageData.items():
        languageDataEnd.append({
            'name': k,
            'value': v
        })
    return languageDataEnd[:15]

def getPubTimeData():
    monthData = {}
    for i in allData:
        if i.uptime in ["未知时间", "未公开", ""]:
            continue
        try:
            date_obj = datetime.strptime(i.uptime, "%Y-%m-%d")
            month = date_obj.strftime("%m")

            if monthData.get(month, -1) == -1:
                monthData[month] = 1
            else:
                monthData[month] += 1
        except ValueError:
            print(f"跳过无效时间格式: {i.uptime}")
        except Exception as e:
            print(f"处理时间时发生错误: {str(e)}, 时间值: {i.uptime}")
    sorted_d = dict(sorted(monthData.items()))
    rateData = {}
    for i in sorted_d:
        if rateData.get(i, -1) == -1:
            rateData[i] = []
    for i in allData:
        if i.uptime in ["未知时间", "未公开", ""]:
            continue
        try:
            date_obj = datetime.strptime(i.uptime, "%Y-%m-%d")
            month = date_obj.strftime("%m")
            for k, v in rateData.items():
                if month == k:
                    v.append(float(i.rate))
        except ValueError:
            print(f"跳过无效时间格式: {i.uptime}")
        except Exception as e:
            print(f"处理时间时发生意外错误: {str(e)}, 时间值: {i.uptime}")
    for k, v in rateData.items():
        if not v:
            rateData[k] = 0.0
            continue
        total = 0
        for item in v:
            total += item
        rateData[k] = round(total / len(v), 1)
    timeX = list(rateData.keys())
    timeY1 = list(monthData.values())
    timeY2 = list(rateData.values())
    timeXNew = []
    for i in timeX:
        timeXNew.append(i + "月")
    return timeXNew, timeY1, timeY2

def getMovieTimeLen():
    timeData=[{'name':'很长','value':0,},
              {'name': '长', 'value': 0, },
              {'name': '中', 'value': 0, },
              {'name': '短', 'value': 0, },
              {'name': '很短', 'value': 0, }]
    for i in allData:
        if int(i.movietime) < 50:
            timeData[4]['value'] += 1
        elif int(i.movietime) < 80:
            timeData[3]['value'] += 1
        elif int(i.movietime) < 120:
            timeData[2]['value'] += 1
        elif int(i.movietime) < 150:
            timeData[1]['value'] += 1
        else:
            timeData[0]['value'] += 1
    return timeData

def getAllHostData():
    xData1 = []
    yData1 = []
    with open("D:\python\豆瓣电影数据分析可视化系统\wordAna\commentTwo.csv", "r", encoding='utf-8') as file:
        reader = csv.reader(file)
        for row in reader:
            try:
                chinese_match = re.search(pattern=r'[\u4e00-\u9fa5]+', string=row[0])
                num_match = re.search(pattern=r'(\d+(\.\d+)?)', string=row[1])
                if chinese_match and num_match:
                    xData1.append(chinese_match.group()[:10])
                    yData1.append(float(num_match.group(1)))
            except Exception as e:
                print(f"处理行失败: {row[:20]}... 错误: {str(e)[:50]}")
    return xData1, yData1

def getAllHostDetail():
    xData = ["0.1", "0.2", "0.3", "0.4", "0.5", "0.6", "0.7", "0.8", "0.9", "1.0"]
    yData = [0] * 10
    commentList = getAllCommentsData()[:300]
    result=[{'name':'积极','value':1},{'name':'消极','value':0}]
    for comment in commentList:
        try:
            sentiment_value = SnowNLP(comment).sentiments
            if sentiment_value >= 0.5:
                result[0]['value'] += 1
            elif sentiment_value >= 0:
                result[1]['value'] += 1
            if sentiment_value >= 0.9:
                yData[9] += 1
            elif sentiment_value >= 0.8:
                yData[8] += 1
            elif sentiment_value >= 0.7:
                yData[7] += 1
            elif sentiment_value >= 0.6:
                yData[6] += 1
            elif sentiment_value >= 0.5:
                yData[5] += 1
            elif sentiment_value >= 0.4:
                yData[4] += 1
            elif sentiment_value >= 0.3:
                yData[3] += 1
            elif sentiment_value >= 0.2:
                yData[2] += 1
            elif sentiment_value >= 0.1:
                yData[1] += 1
            else:
                yData[0] += 1
        except Exception as e:
            print(f"处理评论时出错: {comment}, 错误: {e}")
    return xData, yData,result